package org.sardine.beans;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.sardine.util.Assert;

public class DefaultBeanRegistry implements BeanRegistry{
	
	private static final Logger log = Logger.getLogger(DefaultBeanRegistry.class);
	private final Map<String,Object> beanObjects = Collections.synchronizedMap(new HashMap<String,Object>());

	public void registerBeanObject(String id, Object beanObject) {
		Assert.notNull(id, "id不能为空");
		Assert.notNull(beanObject, "beanObject不能为空");
		
		synchronized(this.beanObjects){
			Object obj = this.beanObjects.get(id);
			/*if(obj != null){
				throw new IllegalStateException("不能将bean注册为id="+id+",该id已被占用,请为bean设置其他id.");
			}*/
			this.beanObjects.put(id, beanObject);
			log.info("成功注册id为\""+id+"\"的实例");
		}
		
	}

	public Object getBeanObject(String id) {
		Assert.notNull(id, "id不能为空");
		return this.beanObjects.get(id);
		
	}

	public boolean containsBeanObject(String id) {
		Assert.notNull(id, "id不能为空");
		return this.beanObjects.containsKey(id);
	}

	public String[] getIds() {
		return (String[])this.beanObjects.keySet().toArray();
	}

	public int getBeanObjectCount() {
		return this.beanObjects.size();
	}
	
	protected Object tryGetBeanObject(String id,ObjectFactory objFactory){
		Assert.notNull(id, "id不能为空");
		Object beanObject = null;
		synchronized(this.beanObjects){
			beanObject = getBeanObject(id);
			if(beanObject == null){
				beanObject = objFactory.getObject();
				//registerBeanObject(id,beanObject);
			}
		}
		return beanObject;
	}

}
